import cn.edu.dgut.Entity.User;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/checkInfo")
public class CheckInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int exsit = 0;

        EntityManager em = (EntityManager) request.getAttribute("_entity.manager");
        String jpql = "select u from User u";
        Query query = em.createQuery(jpql,User.class);
        List<User> resultList = query.getResultList();

        String phone_number = request.getParameter("phone_number");
        if(phone_number!=null) {
            for (User user : resultList) {
                if (user.getPhone_number() != null) {
                    if (user.getPhone_number().contains(phone_number)) {
                        exsit = 1;
                        break;
                    }
                }
            }
        }

        String email = request.getParameter("email");
        if(email!=null) {
            for (User user : resultList) {
                if (user.getEmail() != null) {
                    if (user.getEmail().contains(email)) {
                        exsit = 1;
                        break;
                    }
                }
            }
        }

        String name = request.getParameter("name");
        if(name!=null) {
            for (User user : resultList) {
                if (user.getName() != null) {
                    if (user.getName().contains(name)) {
                        exsit = 1;
                        break;
                    }
                }
            }
        }


        response.setContentType("application/json,charset=utf-8");
        String strJson = "{\"exsit\":\""+exsit+"\"}";
        response.getWriter().println(strJson);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
